<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/11 0011
 * Time: 下午 5:45
 */
namespace app\admin\controller;

use app\admin\model\Groupproduct;
use app\common\BaseHelper;
use think\Request;

class Group extends Base{

    public function _initialize()
    {
        parent::_initialize();
    }

    public function index(){
        $request = $this->request;
        $param = $request->param();
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        if($request->isAjax()){
            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($this->defaultWhere, $where);
            }
            $join = [
                ['__PRODUCT__ p','p.id=a.product_id']
            ];
            $field = 'a.*,p.name,p.price';
            $data = db('groupproduct')->alias('a')->where($where)->join($join)->order('a.create_date DESC')->field($field)->limit($start, $length)->select();
            $count = db('groupproduct')->alias('a')->where($where)->join($join)->field($field)->count();
            foreach($data as $k => &$v)
            {
                $time = time();
                if($v['start_time'] > $time){
                    $v['p_status'] = '待生效';
                }elseif ($v['start_time'] <= $time && $time <= $v['end_time']){
                    $v['p_status'] = '已生效';
                }else{
                    $v['p_status'] = '已过期';
                }
                $v['start_time'] = date('Y-m-d',$v['start_time']);
                $v['end_time'] = date('Y-m-d',$v['end_time']);
            }
            $result = [
                'code' => '0',
                'msg' => '请求成功',
                'data' => $data,
                'count' => $count,
            ];
            return json($result);
        }
        return $this->fetch($this->indexView,[
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    public function add(Request $request){
        return parent::add($request);
    }

    //选择拼团商品
    public function get_product()
    {
        return $this->fetch();
    }

    public function get_product_list()
    {
        $param = $this->request->param();
        $productMdl = model('product');

        $where = [
            'a.status' => 1,
            'a.type' => ['neq', 3] // 不能是加价换购商品
        ];
        if(isset($param['name']) && $param['name']){
            $where['a.name'] = ['like', '%'.$param['name'].'%'];
        }
        $fields = 'a.id,a.name,a.bar_code,a.store_count,a.price,a.status,p.name as typeName';
        $data = $productMdl->alias('a')
            ->where($where)
            ->join('product_category p','a.category_id = p.id')
            ->field($fields)
            ->select();

        $result = [
            'code' => '0',
            'msg' => '请求成功',
            'data' => $data,
        ];
        return json($result);
    }

    public function addPost(Request $request,$redirect = ''){
        if($request->isPost()){
            $param = $request->param();
            $checkinfo = $this->checkparam($param);
            if($checkinfo['pass']){
                if(!empty($param['id'])){
                    //修改
                    $model = Groupproduct::where('id',$param['id'])->find();
                }else{
                    //新增
                    $model = new Groupproduct();
                    $id = BaseHelper::getUUID();
                    $param['id'] = $id;
                }
                $param['group_price'] = $param['group_price'] * 100;
                $param['start_time'] = strtotime($param['start_time']);
                $param['end_time'] = strtotime($param['end_time'] . ' 23:59:59');
                $param['group_succ_time'] = $param['group_succ_time'] * 3600;
                if($model->save($param)){
                    return $this->success('新增成功');
                }else{
                    return $this->error('新增失败');
                }
            }else{
                return $this->error($checkinfo['errmsg']);
            }

        }else{
            return $this->error('非法请求');
        }
    }


    public function edit(Request $request){
        $param = $request->param();
        if(empty($param['id'])){
            return $this->error('缺少参数');
        }
        $data = db('groupproduct')->where('id',$param['id'])->find();
        $product = \app\admin\model\Product::where('id',$data['product_id'])->field('name,price')->find();
        $data['group_price'] = sprintf("%.2f",$data['group_price']/100);
        $data['name'] = $product->name;
        $data['price'] = sprintf("%.2f",$product->price/100);
        $data['group_succ_time'] = $data['group_succ_time']/3600;
        $data['start_time'] = substr(date('Y-m-d',$data['start_time']),0,10);
        $data['end_time'] = substr(date('Y-m-d',$data['end_time']),0,10);
        return $this->fetch('',[
            'data' => $data
        ]);
    }

    /**
     * 启用/禁用
     */
    public function handle(Request $request){
        $model = model('groupproduct');

        if ($request->isPost()) {
            $data = $request->param();

            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

            if($result !== false) {
                return $this->success('操作成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('提交方式错误！');
        }
    }


    /**
     * 参数校验
     * @param $param
     * @return array
     */
    private function checkparam($param){
        $checkinfo = [
            'pass' => true,
            'errmsg' => ''
        ];
        if(empty($param['product_id'])){
            $checkinfo['pass'] = false;
            $checkinfo['errmsg'] = '商品不能为空';
        }
        if(!BaseCheckParam::CheckMoney($param['group_price'])){
            $checkinfo['pass'] = false;
            $checkinfo['errmsg'] = '拼团价不合法';
        }
        if(!BaseCheckParam::GreaterOnePositiveInteger($param['group_succ_count'])){
            $checkinfo['pass'] = false;
            $checkinfo['errmsg'] = '成团人数不合法';
        }

        if(!BaseCheckParam::GreaterZeroPositiveInteger($param['confine_count'])){
            $checkinfo['pass'] = false;
            $checkinfo['errmsg'] = '限购数量不合法';
        }

        if(strtotime($param['start_time']) >= strtotime($param['end_time'] . ' 23:59:59')){
            $checkinfo['pass'] = false;
            $checkinfo['errmsg'] = '开始时间不能大于结束时间';
        }

        return $checkinfo;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['name']) && $param['name']){
            $where['p.name'] = ['like', '%'.$param['name'].'%'];
        }
        if(isset($param['p_status']) && $param['p_status']){
            $nowtime = time();
            if($param['p_status'] == 1){
                $where['a.start_time'] = ['elt',$nowtime];
                $where['a.end_time'] = ['egt',$nowtime];
            }elseif ($param['p_status'] == 2){
                $where['a.start_time'] = ['gt',$nowtime];
            }elseif ($param['p_status'] == 3){
                $where['a.end_time'] = ['lt',$nowtime];
            }
        }
        return $where;
    }


}